// BcmLibTest.c
//
// A library for SPI transfers at ~1MHz SCLK with manually managed CS pins.
//
// Based on the example code provided by Mike McCauley at
// http://www.open.com.au/mikem/bcm2835
//
// Author: Daniel Hearn
// Date: 23 Feb 2013

#include "BcmLib.h"

//****************************************************************************/
//	Library Functions
//****************************************************************************/
int initMySpi(uint8_t *csPins, int len){
    if(!bcm2835_init())
        return 1;

    bcm2835_spi_begin();
    bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);      // The default
    bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);                   // The default
    bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_256);   // 1MHz
    bcm2835_spi_chipSelect(BCM2835_SPI_CS_NONE);                  // We will manage CS ourselves

    int i;
    for(i = 0; i < len; i++){                                     // Set all GPIO pins to outputs
            bcm2835_gpio_fsel(csPins[i], BCM2835_GPIO_FSEL_OUTP); 
            bcm2835_gpio_write(csPins[i], HIGH);                  // Default to HIGH for CS   
    }
    return 0;
}

void mySpiTransfer(char *tbuf, char *rbuf, uint32_t len, uint8_t cs){
    bcm2835_gpio_write(cs, LOW);
	bcm2835_spi_transfernb(tbuf, rbuf, len);
    bcm2835_gpio_write(cs, HIGH);
	return;
}

